from zope.interface import implements

from twisted.plugin import IPlugin
from twisted.internet import defer

from pyhnode import interfaces, config

import socket, fcntl, struct, time

class ipv4addrPlugin(object):

    implements(IPlugin, interfaces.IPlugins)

    def getNames(self):
        return ["ipv4addr"]

    def getOsValue(self, name):
        pass
    
    def getValue(self, name):
        return defer.succeed(self.getOsValue(name))

    def getAlert(self, name):
        return False

    def getConfig(self, name):
        return ";title:ipv4addr|ipv4addr#stype:GAUGE;label:ipv4_address"

    def configure(self):
        if(config.conf.get('general','platform') == 'linux'):
            self.getOsValue = self.getLinuxValue
        self.iface = config.conf.get('ipv4addr','interface')
    
    def getLinuxValue(self, name):
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        ret = socket.inet_ntoa(fcntl.ioctl(
            s.fileno(),
            0x8915,  # SIOCGIFADDR
            struct.pack('256s', self.iface[:15])
        )[20:24])
        return [str(int(time.time())), {"ipv4addr" : str(ret)}]


tp = ipv4addrPlugin()
